package main.java.indi.zyj.coderecord;

public class _03_generateMatrix {

    public static void main(String[] args) {

    }
    public int[][] generateMatrix(int n) {

        int loop = 0;
        int start = 0;
        int num = 1;
        int[][] matrix = new int[n][n];
        int i, j;

        while (loop++ < n>>1){

            // 左上到左右
            for (i = start; i < n - loop; i++) {
                matrix[start][i] = num++;
            }

            // 右上到右下
            for (j = start; j < n - loop; j++) {
                matrix[j][i] = num++;
            }

            // 右下到左下
            for (; i >= loop ; i--) {
                matrix[j][i] = num++;
            }

            // 左下到左上
            for (; j >= loop ; j--) {
                matrix[j][i] = num++;
            }

            start++;

        }

        if (n % 2 == 1) {
            matrix[start][start] = num;
        }

        return matrix;

    }
}
